package com.song.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.song.constant.MessageConstant;
import com.song.dto.UserLoginDTO;
import com.song.entity.User;
import com.song.exception.LoginFailedException;
import com.song.mapper.UserMapper;
import com.song.properties.WeChatProperties;
import com.song.service.UserService;
import com.song.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    private final static String WX_OPEN_REDIRECT_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public User userWxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口，获取微信用户信息(opnenid:用户唯一标识)
        Map<String,String> paramMap = new HashMap();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        HttpClientUtil.doGet(WX_OPEN_REDIRECT_URL,paramMap);
        //发送请求并获取结果(JSON)
        JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doGet(WX_OPEN_REDIRECT_URL,paramMap));
        //获取返回结果中的openid
        String openid = jsonObject.getString("openid");
        if (openid == null) throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        //根据openid查询数据库，判断当前用户是否为新用户
        User user = userMapper.getUserByOpenid(openid);
        if( user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
                    userMapper.addUser(user);
        }

        return user;
    }
}
